document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const backToTopButton = document.getElementById('back-to-top');
    const header = document.querySelector('header');
    const loginModal = document.getElementById('login-modal');
    const registerModal = document.getElementById('register-modal');
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const notification = document.getElementById('notification');

    // 认证相关元素
    const authButtons = document.getElementById('auth-buttons');
    const userProfile = document.getElementById('user-profile');
    const usernameDisplay = document.getElementById('username-display');
    const logoutBtn = document.getElementById('logout-btn');

    // 模态框相关元素
    const loginButton = loginForm.querySelector('button[type="submit"]');
    const registerButton = registerForm.querySelector('button[type="submit"]');

    // 模拟用户状态
    let currentUser = null;
    // 默认登录时没有勾选“记住我”
    let rememberUser = false;
    // 初始化页面
    initPage();

    // 事件监听器 - 滚动处理
    window.addEventListener('scroll', handleScroll);

    // 平滑滚动
    setupSmoothScroll();

    // 模态框控制
    setupModalControls();

    // 表单验证
    setupFormValidation();

    // 密码显示/隐藏切换
    setupPasswordToggles();

    // 通知控制
    setupNotification();

    // 初始化页面状态
    function initPage() {
        // 检查本地存储中是否有用户信息，并且是在"记住我"状态下保存的
        const savedUser = localStorage.getItem('currentUser');
        const rememberState = localStorage.getItem('rememberUser') === 'true';

        if (savedUser && rememberState) {
            currentUser = JSON.parse(savedUser);
            rememberUser = true;
            updateAuthUI();
        } else {
            // 清除可能残留的密码
            document.getElementById('login-password').value = '';
        }
    }

    // 处理滚动事件
    function handleScroll() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

        // 控制返回顶部按钮显示
        if (scrollTop > 300) {
            backToTopButton.classList.remove('opacity-0', 'invisible');
            backToTopButton.classList.add('opacity-100', 'visible');
        } else {
            backToTopButton.classList.add('opacity-0', 'invisible');
            backToTopButton.classList.remove('opacity-100', 'visible');
        }

        // 导航栏阴影效果
        if (scrollTop > 100) {
            header.classList.add('shadow-md');
            header.classList.remove('shadow-sm');
        } else {
            header.classList.remove('shadow-md');
            header.classList.add('shadow-sm');
        }
    }

    // 设置平滑滚动
    function setupSmoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();

                const targetId = this.getAttribute('href');
                if (targetId === '#') return;

                const targetElement = document.querySelector(targetId);
                if (targetElement) {
                    targetElement.scrollIntoView({
                        behavior: 'smooth'
                    });
                }
            });
        });
    }

    // 设置模态框控制
    function setupModalControls() {
        // 获取相关元素
        const loginLink = document.getElementById('login-link');
        const registerLink = document.getElementById('register-link');
        const heroRegisterBtn = document.getElementById('hero-register-btn');
        const closeLogin = document.getElementById('close-login');
        const closeRegister = document.getElementById('close-register');
        const switchToRegister = document.getElementById('switch-to-register');
        const switchToLogin = document.getElementById('switch-to-login');

        // 打开登录模态框
        loginLink.addEventListener('click', openLoginModal);

        // 打开注册模态框
        registerLink.addEventListener('click', openRegisterModal);
        if (heroRegisterBtn) {
            heroRegisterBtn.addEventListener('click', openRegisterModal);
        }

        // 关闭模态框
        closeLogin.addEventListener('click', closeLoginModal);
        closeRegister.addEventListener('click', closeRegisterModal);

        // 切换到注册
        switchToRegister.addEventListener('click', function() {
            closeLoginModal();
            setTimeout(openRegisterModal, 300);
        });

        // 切换到登录
        switchToLogin.addEventListener('click', function() {
            closeRegisterModal();
            setTimeout(openLoginModal, 300);
        });

        // 点击模态框外部关闭
        loginModal.addEventListener('click', function(e) {
            if (e.target === loginModal) {
                closeLoginModal();
            }
        });

        registerModal.addEventListener('click', function(e) {
            if (e.target === registerModal) {
                closeRegisterModal();
            }
        });
    }

    // 打开登录模态框
    function openLoginModal() {
        requestAnimationFrame(() => {
            loginModal.classList.remove('opacity-0', 'invisible');
            requestAnimationFrame(() => {
                loginModal.querySelector('.scale-95').classList.remove('scale-95');
                loginModal.querySelector('.scale-100').classList.add('scale-100');
                document.body.style.overflow = 'hidden';
            });
        });
    }

    // 关闭登录模态框
    function closeLoginModal() {
        requestAnimationFrame(() => {
            loginModal.classList.add('opacity-0', 'invisible');
            loginModal.querySelector('.scale-100').classList.remove('scale-100');
            loginModal.querySelector('.scale-95').classList.add('scale-95');
            document.body.style.overflow = '';

            // 重置表单
            loginForm.reset();
            hideLoginErrors();
        });
    }

    // 打开注册模态框
    function openRegisterModal() {
        requestAnimationFrame(() => {
            registerModal.classList.remove('opacity-0', 'invisible');
            requestAnimationFrame(() => {
                registerModal.querySelector('.scale-95').classList.remove('scale-95');
                registerModal.querySelector('.scale-100').classList.add('scale-100');
                document.body.style.overflow = 'hidden';
            });
        });
    }

    // 关闭注册模态框
    function closeRegisterModal() {
        requestAnimationFrame(() => {
            registerModal.classList.add('opacity-0', 'invisible');
            registerModal.querySelector('.scale-100').classList.remove('scale-100');
            registerModal.querySelector('.scale-95').classList.add('scale-95');
            document.body.style.overflow = '';
            // 重置表单
            registerForm.reset();
            hideRegisterErrors();
        });
    }

    // 隐藏登录错误提示
    function hideLoginErrors() {
        document.getElementById('login-email-error').classList.add('hidden');
        document.getElementById('login-password-error').classList.add('hidden');
    }

    // 隐藏注册错误提示
    function hideRegisterErrors() {
        document.getElementById('register-name-error').classList.add('hidden');
        document.getElementById('register-email-error').classList.add('hidden');
        document.getElementById('register-password-error').classList.add('hidden');
        document.getElementById('register-confirm-password-error').classList.add('hidden');
    }

    // 设置表单验证
    function setupFormValidation() {
        // 登录表单验证
        loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        let isValid = true;
        hideLoginErrors();

        const email = document.getElementById('login-email').value.trim();
        const password = document.getElementById('login-password').value;

        // 验证邮箱
        if (!email) {
            document.getElementById('login-email-error').textContent = '请输入邮箱';
            document.getElementById('login-email-error').classList.remove('hidden');
            isValid = false;
        } else if (!/\S+@\S+\.\S+/.test(email)) {
            document.getElementById('login-email-error').textContent = '请输入有效的邮箱地址';
            document.getElementById('login-email-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证密码（仅保留非空检查）
        if (!password) {
            document.getElementById('login-password-error').textContent = '请输入密码';
            document.getElementById('login-password-error').classList.remove('hidden');
            isValid = false;
        }

        if (isValid) {
            // 模拟登录API请求
            simulateLogin(email, password);
        }
    });

        // 注册表单验证
        registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        let isValid = true;
        hideRegisterErrors();

        const name = document.getElementById('register-name').value.trim();
        const email = document.getElementById('register-email').value.trim();
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('register-confirm-password').value;

        // 验证姓名
        if (!name) {
            document.getElementById('register-name-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证邮箱
        if (!email) {
            document.getElementById('register-email-error').textContent = '请输入邮箱';
            document.getElementById('register-email-error').classList.remove('hidden');
            isValid = false;
        } else if (!/\S+@\S+\.\S+/.test(email)) {
            document.getElementById('register-email-error').textContent = '请输入有效的邮箱地址';
            document.getElementById('register-email-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证密码（仅保留非空检查）
        if (!password) {
            document.getElementById('register-password-error').textContent = '请输入密码';
            document.getElementById('register-password-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证确认密码
        if (!confirmPassword) {
            document.getElementById('register-confirm-password-error').textContent = '请确认密码';
            document.getElementById('register-confirm-password-error').classList.remove('hidden');
            isValid = false;
        } else if (confirmPassword !== password) {
            document.getElementById('register-confirm-password-error').classList.remove('hidden');
            isValid = false;
        }

        if (isValid) {
            // 模拟注册API请求
            simulateRegister(name, email, password);
        }
    });
    }

    // 设置密码显示/隐藏切换
    function setupPasswordToggles() {
        // 登录密码切换
        document.getElementById('toggle-login-password').addEventListener('click', function() {
            togglePasswordVisibility('login-password', 'login-password-icon');
        });

        // 注册密码切换
        document.getElementById('toggle-register-password').addEventListener('click', function() {
            togglePasswordVisibility('register-password', 'register-password-icon');
        });

        // 注册确认密码切换
        document.getElementById('toggle-register-confirm-password').addEventListener('click', function() {
            togglePasswordVisibility('register-confirm-password', 'register-confirm-password-icon');
        });
    }

    // 切换密码可见性
    function togglePasswordVisibility(inputId, iconId) {
        const passwordInput = document.getElementById(inputId);
        const icon = document.getElementById(iconId);

        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    }

    // 设置通知
    function setupNotification() {
        document.getElementById('close-notification').addEventListener('click', closeNotification);
    }

    // 显示通知
    function showNotification(title, message, type = 'success') {
        const notificationTitle = document.getElementById('notification-title');
        const notificationMessage = document.getElementById('notification-message');
        const notificationIcon = document.getElementById('notification-icon');

        notificationTitle.textContent = title;
        notificationMessage.textContent = message;

        // 设置图标和颜色
        if (type === 'success') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-green-100 flex items-center justify-center text-green-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-check"></i>';
        } else if (type === 'error') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-red-100 flex items-center justify-center text-red-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-times"></i>';
        } else if (type === 'warning') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-yellow-100 flex items-center justify-center text-yellow-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
        } else if (type === 'info') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-info-circle"></i>';
        }

        // 显示通知
        requestAnimationFrame(() => {
            notification.classList.remove('translate-x-full');

            // 3秒后自动关闭
            setTimeout(() => {
                closeNotification();
            }, 3000);
        });
    }

    // 关闭通知
    function closeNotification() {
        requestAnimationFrame(() => {
            notification.classList.add('translate-x-full');
        });
    }

    // 模拟登录API请求
    function simulateLogin(email, password) {
        // 显示加载状态
        const originalText = loginButton.innerHTML;
        loginButton.disabled = true;
        loginButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> 登录中...';

        // 使用setTimeout模拟API请求延迟
        setTimeout(() => {
            // 恢复按钮状态
            loginButton.disabled = false;
            loginButton.innerHTML = originalText;

            // 模拟登录成功，创建用户对象
            const user = {
                email,
                username: email.split('@')[0], // 使用邮箱前缀作为用户名
                id: Date.now().toString()
            };

            handleLoginSuccess(user);
            showNotification('登录成功', `欢迎回来，${user.username}!`);
            closeLoginModal();
        }, 1500);
    }

    // 模拟注册API请求
    function simulateRegister(name, email, password) {
        // 显示加载状态
        const originalText = registerButton.innerHTML;
        registerButton.disabled = true;
        registerButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> 注册中...';

        // 使用setTimeout模拟API请求延迟
        setTimeout(() => {
            // 恢复按钮状态
            registerButton.disabled = false;
            registerButton.innerHTML = originalText;

            // 模拟注册成功
            showNotification('注册成功', '恭喜您注册成功，请登录！');
            closeRegisterModal();

            // 延迟后打开登录模态框
            setTimeout(() => {
                openLoginModal();

                // 自动填充注册邮箱
                const loginEmailInput = document.getElementById('login-email');
                if (loginEmailInput) {
                    loginEmailInput.value = email;
                }
            }, 300);
        }, 1500);
    }

    // 更新认证UI（登录/退出状态）
    function updateAuthUI() {
        if (currentUser) {
            // 已登录：显示用户名和退出按钮
            authButtons.classList.add('hidden');
            userProfile.classList.remove('hidden');
            usernameDisplay.textContent = currentUser.username || currentUser.email;
        } else {
            // 未登录：显示登录/注册按钮
            authButtons.classList.remove('hidden');
            userProfile.classList.add('hidden');
        }
    }

    // 登录成功后的处理
    function handleLoginSuccess(user) {
        currentUser = user;
        // 仅在勾选"记住我"时保存到 localStorage
        const rememberMeChecked = document.getElementById('remember-me').checked;
        if (rememberMeChecked) {
            localStorage.setItem('currentUser', JSON.stringify(user));
            localStorage.setItem('rememberUser', 'true');
            rememberUser = true;
        } else {
            // 不保存用户信息，并且清除可能的旧数据
            localStorage.removeItem('currentUser');
            localStorage.removeItem('rememberUser');
            rememberUser = false;
        }

        updateAuthUI();
    }

    // 退出登录
    logoutBtn.addEventListener('click', function() {
        currentUser = null;
        // 清除本地存储的用户信息
        localStorage.removeItem('currentUser');
        localStorage.removeItem('rememberUser');
        // 清除登录表单中的密码
        if(rememberUser === false)
            document.getElementById('login-password').value = '';
        
        updateAuthUI();
        showNotification('已退出登录', '您已成功退出账户', 'info');
    });

    // 返回顶部按钮点击事件
    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
});